
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- You can adjust the viewport settings as needed -->
    <meta name="viewport" content="width=1200, initial-scale=1.0">
    <title>Equation Verification</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #f0f0f0;
            border-bottom: 1px solid #ddd;
        }
        .content {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        .pdf-viewer {
            flex: 2; /* Increased from 1 to 2 to make PDF larger */
            border-right: 1px solid #ddd;
            overflow: hidden;
            position: relative;
        }
        /* Updated PDF container size */
        #pdf-container {
            width: 200%;  /* New fixed width */
            height: 200%;  /* New fixed height */
            overflow: auto;
        }
        #zoom-controls {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 100;
            background-color: white;
            padding: 5px;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        }
        #zoom-controls button {
            margin: 0 5px;
            padding: 5px 10px;
            cursor: pointer;
        }
        .tests-panel {
            width: 1000px;
            overflow-y: auto;
            padding: 10px;
        }
        .test-item {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            transition: background-color 0.2s;
        }
        .test-item.verified {
            background-color: #d4edda;
        }
        .test-item.rejected {
            background-color: #f8d7da;
        }
        /* The equation-display now stores the raw LaTeX in a data attribute */
        .equation-display {
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f9f9f9;
            overflow-x: auto;
            font-size: 1.2em; /* Larger font for equations */
        }
        .button-group {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
        }
        .button-group button {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .verify-button {
            background-color: #28a745;
            color: white;
        }
        .reject-button {
            background-color: #dc3545;
            color: white;
        }
        .edit-button {
            background-color: #007bff;
            color: white;
        }
        .navigation {
            display: flex;
            align-items: center;
        }
        .status {
            margin-left: 20px;
        }
        .progress-bar {
            height: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
            margin-top: 5px;
            overflow: hidden;
        }
        .progress {
            height: 100%;
            background-color: #007bff;
            width: 0%;
        }
        /* Make MathJax equations more visible */
        .MathJax {
            font-size: 120% !important;
        }
    </style>
</head>
<body>
    <div class="header">
        <div>
            <h2>PDF: {{ pdf_name }}</h2>
            <form method="post" action="/reject_all" id="reject-all-form" style="display:inline;">
                <button type="button" onclick="rejectAll('{{ pdf_name }}')">Reject All Equations</button>
            </form>
        </div>
        <div class="navigation">
            <form method="post" action="/prev_pdf" style="display:inline;">
                <button type="submit" {% if pdf_index == 0 %}disabled{% endif %}>Previous</button>
            </form>
            <span style="margin: 0 10px;">{{ pdf_index + 1 }} / {{ total_pdfs }}</span>
            <form method="post" action="/next_pdf" style="display:inline;">
                <button type="submit">Next</button>
            </form>
            <div class="status">
                <div>Completion: {{ "%.1f"|format(stats.completion) }}%</div>
                <div class="progress-bar">
                    <div class="progress" style="width: {{ stats.completion }}%;"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="content">
        <div class="pdf-viewer">
            <div id="zoom-controls">
                <button onclick="changeZoom(0.2)">+</button>
                <button onclick="changeZoom(-0.2)">-</button>
                <button onclick="resetZoom()">Reset</button>
            </div>
            <div id="pdf-container"></div>
        </div>
        <div class="tests-panel">
            <h3>Equations ({{ tests|length }})</h3>
            {% for test in tests %}
            <!-- Added data-latex attribute to store raw LaTeX -->
            <div class="test-item {% if test.checked == 'verified' %}verified{% elif test.checked == 'rejected' %}rejected{% endif %}" id="test-{{ test.id }}">
                <div class="equation-display" data-latex="{{ test.text|e }}">
                    {{ test.text|safe }}
                </div>
                <div class="button-group">
                    <button class="verify-button" onclick="updateTest('{{ test.id }}', '{{ test.pdf }}', 'checked', 'verified')">Verify</button>
                    <button class="reject-button" onclick="updateTest('{{ test.id }}', '{{ test.pdf }}', 'checked', 'rejected')">Reject</button>
                    <!-- New Edit button -->
                    <button class="edit-button" onclick="enableEdit('{{ test.id }}', '{{ test.pdf }}')">Edit</button>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <script>
        // Set up PDF.js
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
        
        // Track current zoom level
        let currentScale = 2.0; // Initial larger scale
        let pdfDoc = null;
        let pageNum = 1;
        let canvas = null;
        
        // Load the PDF
        const loadingTask = pdfjsLib.getDocument('{{ pdf_path }}');
        loadingTask.promise.then(function(pdf) {
            pdfDoc = pdf;
            renderPage(pageNum);
        });
        
        // Function to render a page with the current scale
        function renderPage(num) {
            pdfDoc.getPage(num).then(function(page) {
                const viewport = page.getViewport({ scale: currentScale });
                if (!canvas) {
                    canvas = document.createElement('canvas');
                    document.getElementById('pdf-container').appendChild(canvas);
                }
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                const renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                page.render(renderContext);
            });
        }
        
        // Function to change zoom level
        function changeZoom(delta) {
            currentScale += delta;
            if (currentScale < 0.5) currentScale = 0.5;
            if (currentScale > 5) currentScale = 5;
            renderPage(pageNum);
        }
        
        // Function to reset zoom
        function resetZoom() {
            currentScale = 2.0;
            renderPage(pageNum);
        }
        
        // Function to update a test – used by both verify/reject and edit
        function updateTest(testId, pdfName, field, value) {
            fetch('/update_test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: testId,
                    pdf: pdfName,
                    field: field,
                    value: value
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    const testElement = document.getElementById(`test-${testId}`);
                    testElement.classList.remove('verified', 'rejected');
                    // Only update the class if the field updated is "checked".
                    if (field === 'checked') {
                        testElement.classList.add(value);
                    }
                }
            });
        }
        
        // New function to enable editing the LaTeX equation
        function enableEdit(testId, pdfName) {
            let testElement = document.getElementById("test-" + testId);
            let equationDisplay = testElement.querySelector(".equation-display");
            // Retrieve the raw LaTeX from the data attribute
            let rawLatex = equationDisplay.getAttribute('data-latex');
            // Save the current rendered HTML in case of cancellation
            let originalHTML = equationDisplay.innerHTML;
            
            // Create a textarea for editing the LaTeX
            let textarea = document.createElement("textarea");
            textarea.id = "edit-input-" + testId;
            // Use the stored raw LaTeX if available; otherwise, fallback to textContent
            textarea.value = rawLatex ? rawLatex : equationDisplay.textContent.trim();
            textarea.style.width = "100%";
            textarea.rows = 3;
            
            // Create Save button to commit changes
            let saveButton = document.createElement("button");
            saveButton.innerText = "Save";
            saveButton.onclick = function() {
                let newText = textarea.value;
                // Update the test via AJAX – updating the 'text' field
                updateTest(testId, pdfName, "text", newText);
                // Update the data-latex attribute to hold the new raw LaTeX code
                equationDisplay.setAttribute('data-latex', newText);
                // Replace the display content with the wrapped LaTeX for MathJax to process
                equationDisplay.innerHTML = '$$' + newText + '$$';
                if (typeof MathJax !== 'undefined') {
                    MathJax.typeset();
                }
                // Clean up the temporary editing elements
                textarea.remove();
                saveButton.remove();
                cancelButton.remove();
            };
            
            // Create Cancel button to revert changes
            let cancelButton = document.createElement("button");
            cancelButton.innerText = "Cancel";
            cancelButton.onclick = function() {
                equationDisplay.innerHTML = originalHTML;
                textarea.remove();
                saveButton.remove();
                cancelButton.remove();
            };
            
            // Show the editing interface: clear the display and insert the textarea
            equationDisplay.innerHTML = "";
            equationDisplay.appendChild(textarea);
            // Append buttons to the test element (or you can choose to append them elsewhere)
            testElement.appendChild(saveButton);
            testElement.appendChild(cancelButton);
        }
        
        // Function to reject all tests for a PDF
        function rejectAll(pdfName) {
            if (confirm('Are you sure you want to reject all equations for this PDF?')) {
                fetch('/reject_all', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        pdf: pdfName
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        const testElements = document.querySelectorAll('.test-item');
                        testElements.forEach(element => {
                            element.classList.remove('verified');
                            element.classList.add('rejected');
                        });
                    }
                });
            }
        }

        // Process LaTeX equations on page load: wrap plain text with $$ and trigger MathJax typesetting
        document.addEventListener('DOMContentLoaded', function() {
            const equationDisplays = document.querySelectorAll('.equation-display');
            equationDisplays.forEach(display => {
                let equation = display.textContent.trim();
                if (!equation.startsWith('$$')) {
                    display.innerHTML = '$$' + equation + '$$';
                }
            });
            if (typeof MathJax !== 'undefined') {
                MathJax.typeset();
            }
        });
    </script>
</body>
</html>
    